package net.hserver.gateway.core.strategy.imp;

import net.hserver.gateway.core.strategy.Chose;
import net.hserver.gateway.core.strategy.ServerNode;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author hxm
 */
public class MinimumConnectionStrategy<T> implements Chose<T> {

    private List<ServerNode> hosts;

    private static MinimumConnectionStrategy minimumConnectionStrategy;

    private MinimumConnectionStrategy() {
    }

    @Override
    public T choseInfo(String ip) {
        long temp = -1;
        ServerNode serverNode = null;
        for (ServerNode host : hosts) {
            if (temp == -1) {
                temp = host.getConnectNum();
                serverNode = host;
            } else if (host.getConnectNum() < temp) {
                temp = host.getConnectNum();
                serverNode = host;
            }
        }
        return (T) serverNode;

    }

    public static <T> MinimumConnectionStrategy getInstance(List<T> hosts) {
        if (minimumConnectionStrategy == null) {
            synchronized (RandomStrategy.class) {
                if (minimumConnectionStrategy == null) {
                    minimumConnectionStrategy = new MinimumConnectionStrategy();
                }
            }
        }
        minimumConnectionStrategy.hosts = hosts;
        return minimumConnectionStrategy;
    }
}
